# -*- coding: utf-8 -*-
# @Time    : 2019/10/31 11:13
# @Author  : 岳保保
# @File    : AuthorityRequest.py
# @Software: PyCharm
from django import forms
from django.core.exceptions import ValidationError

from crm.models import Authority, Role
from utils.utils.request import Request, ERROR_MSG


class AuthorityForm(Request):
    """权限form验证"""

    class Meta:
        model = Authority
        fields = [
            "title",
            "type",
            "url",
            "code",
            "pid",
        ]

    title = forms.CharField(max_length=32, label='权限名称', error_messages=ERROR_MSG)
    type = forms.ChoiceField(label='资源类型', choices=[("menu", "菜单权限"), ("button", "按钮权限")], error_messages=ERROR_MSG)
    url = forms.CharField(max_length=128, label='访问url地址', required=False, error_messages=ERROR_MSG)
    code = forms.CharField(max_length=32, label='权限代码字符', required=False, error_messages=ERROR_MSG)
    pid = forms.ModelChoiceField(label='父级权限', queryset=Authority.objects.all(),
                                 required=False, error_messages=ERROR_MSG)

    def clean_title(self):
        title = self.cleaned_data.get("title")
        if self.instance:
            obj = Authority.objects.filter(title=title).exclude(pk=self.instance.pk).first()
        else:
            obj = Authority.objects.filter(title=title).first()

        if obj:
            raise ValidationError("权限名称已存在！")
        else:
            return title

    def clean_code(self):
        code = self.cleaned_data.get("code")
        if self.instance:
            obj = Authority.objects.filter(code=code).exclude(pk=self.instance.pk).first()
        else:
            obj = Authority.objects.filter(code=code).first()
        if obj:
            raise ValidationError("权限代码已存在！")
        else:
            return code

    def clean(self):
        pid = self.cleaned_data.get("pid")
        if pid:
            if pid.levels:
                self.cleaned_data['levels'] = '%s/%d' % (pid.levels, pid.pk)
            else:
                self.cleaned_data['levels'] = str(pid.pk)
        return self.cleaned_data


class RoleForm(Request):
    """角色Form验证"""

    class Meta:
        model = Role
        fields = "__all__"

    name = forms.CharField(max_length=32, label='角色名称', error_messages=ERROR_MSG)
    type = forms.ChoiceField(label="角色类型", choices=[(1, "超级用户"), (2, "管理员"), (3, "普通用户")], error_messages=ERROR_MSG)

    # 多对多字段必须与关联的字段名称一致
    authority = forms.ModelMultipleChoiceField(label='角色所拥有的权限', queryset=Authority.objects.all(),
                                               error_messages=ERROR_MSG)

    def clean_name(self):
        name = self.cleaned_data.get("name")
        if self.instance:
            obj = Role.objects.filter(name=name).exclude(pk=self.instance.pk).first()
        else:
            obj = Role.objects.filter(name=name).first()
        if obj:
            raise ValidationError("角色名称已存在！")
        else:
            return name
